﻿using System;
using System.Diagnostics;
using PostSharp.Aspects;

namespace Theoreme.Teaching.AOP.Sample01
{
    [Serializable]
    public sealed class InstrumentPercentOfTimeAttribute : PerformanceCounterAttribute
    {
        private static readonly Stopwatch stopwatch = Stopwatch.StartNew();

        public InstrumentPercentOfTimeAttribute( string categoryName, string counterName ) : base( categoryName, counterName,
                                                                                                   PerformanceCounterType.CounterTimer )
        {
        }

        /// <summary>
        /// Method invoked before the execution of the method to which the current
        /// aspect is applied.
        /// </summary>
        /// <param name="args">Unused.</param>
        public override void OnEntry( MethodExecutionArgs args )
        {
            args.MethodExecutionTag = stopwatch.ElapsedTicks;
            base.OnEntry( args );
        }

        /// <summary>
        /// Method invoked after the execution of the method to which the current
        /// aspect is applied.
        /// </summary>
        /// <param name="args">Unused.</param>
        public override void OnExit( MethodExecutionArgs args )
        {
            if ( this.PerformanceCounter != null )
            {
                long time = stopwatch.ElapsedTicks - (long) args.MethodExecutionTag;
                this.PerformanceCounter.IncrementBy( time );
                //  this.BasePerformanceCounter.Increment();
            }
        }
    }
}